package cn.itcast.controller.company;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.company.Company;
import cn.itcast.service.company.CompanyService;
import cn.itcast.vo.PageBean;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/company")
public class CompanyController extends BaseController {

    @Reference
    private CompanyService companyService;

    @RequiresPermissions("企业管理") //当前登录人有”企业管理“管理权限才能进入到这个方法
    @RequestMapping(value = "/list",name = "展示企业列表数据")
    public String findAll(@RequestParam(name="page",defaultValue = "1") Integer pageNum,
                         @RequestParam(name="pageSize",defaultValue = "2") Integer pageSize){
//        List<Company> companyList = companyService.findAll();
//        PageBean pageBean = companyService.findPage(pageNum,pageSize);
        PageInfo<Company> pageInfo = companyService.findPage(pageNum,pageSize);
        request.setAttribute("page",pageInfo); //这个 “page” 不能写错，因为页面就是取的是page中的值
        return "company/company-list";
    }

    @RequestMapping(value = "/toAdd",name = "跳转到新增企业的页面")
    public String toAdd( ){
        return "company/company-add";
    }

    @RequestMapping(value = "/edit",name = "保存企业方法")
    public String save(Company company){
//        新增 id上是没有值的
//        修改 id是有值的
        if(StringUtils.isEmpty(company.getId())){ //ID为空 新增
            company.setId(UUID.randomUUID().toString());
            companyService.save(company);
        }else{
            companyService.update(company);
        }
        return "redirect:/company/list.do"; //重定向到企业列表中
    }

    @RequestMapping(value = "/toUpdate",name = "进入到企业编辑页面")
    public String toUpdate(String id){
        Company company = companyService.findById(id);
        request.setAttribute("company",company);
        return "company/company-add";
    }
    @RequestMapping(value = "/delete",name = "删除企业数据")
    public String delete(String id){
        companyService.deleteById(id);
        return "redirect:/company/list.do";
    }

}
